package modules

import (
	"fmt"
	"github.com/streadway/amqp"
	"gspeed/bootstrap/global"
)

type amqpClient struct {
	connection *amqp.Connection
}

var Amqp amqpClient

func (a *amqpClient) New() *amqp.Connection {
	if a.connection != nil {
		return a.connection
	}
	// 设置配置默认值
	global.Config.SetDefault("rabbitmq.user", "root")
	global.Config.SetDefault("rabbitmq.password", "")
	global.Config.SetDefault("rabbitmq.host", "localhost")
	global.Config.SetDefault("rabbitmq.port", 5672)
	global.Config.SetDefault("rabbitmq.vhost", "/")
	// 链接amqp
	var err error
	a.connection, err = amqp.Dial(fmt.Sprintf("amqp://%s:%s@%s:%d/%s",
		global.Config.GetString("rabbitmq.user"),
		global.Config.GetString("rabbitmq.password"),
		global.Config.GetString("rabbitmq.host"),
		global.Config.GetInt("rabbitmq.port"),
		global.Config.GetString("rabbitmq.vhost"),
	))
	if err != nil {
		fmt.Println(err.Error())
	}
	return a.connection
}
